package service

import (
    "errors"
    "{{.ProjectModule}}/models"
    "{{.ProjectModule}}/repository"
)

type {{.StructName}}Service struct {
    Repo *repository.{{.StructName}}Repository
}

func New{{.StructName}}Service(repo *repository.{{.StructName}}Repository) *{{.StructName}}Service {
    return &{{.StructName}}Service{Repo: repo}
}

func (s *{{.StructName}}Service) Create{{.StructName}}({{.VarName}} *models.{{.StructName}}) error {
    return s.Repo.Create{{.StructName}}({{.VarName}})
}

func (s *{{.StructName}}Service) GetAll{{.StructName}}s() ([]models.{{.StructName}}, error) {
    return s.Repo.GetAll{{.StructName}}s()
}

func (s *{{.StructName}}Service) Get{{.StructName}}ByID(id uint) (*models.{{.StructName}}, error) {
    if id == 0 {
        return nil, errors.New("invalid id")
    }
    return s.Repo.Get{{.StructName}}ByID(id)
}

func (s *{{.StructName}}Service) Update{{.StructName}}(id uint, {{.VarName}} *models.{{.StructName}}) error {
    existing, err := s.Repo.Get{{.StructName}}ByID(id)
    if err != nil {
        return errors.New("record not found")
    }

    // Copy fields (skip primary key)
    {{- range .Fields}}
    {{- if not .IsPK}}
    existing.{{.Name}} = {{$.VarName}}.{{.Name}}
    {{- end}}
    {{- end}}

    return s.Repo.Update{{.StructName}}(existing)
}

func (s *{{.StructName}}Service) Delete{{.StructName}}(id uint) error {
    _, err := s.Repo.Get{{.StructName}}ByID(id)
    if err != nil {
        return errors.New("record not found")
    }
    return s.Repo.Delete{{.StructName}}(id)
}